package com.zxbg.service.impl.loginServiceImpl;

import com.zxbg.dao.AppDao;
import com.zxbg.dao.EmployeeDao;
import com.zxbg.domain.App;
import com.zxbg.domain.Employee;
import com.zxbg.service.loginService.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    AppDao appDao;

    @Override
    public Employee getEmployeeByEmployeeIdAndPassword(String employee_id, String password, Integer tenant_id) {
        if(tenant_id == null) {
            Employee employee = employeeDao.getEmployeeByEmployeeIdAndPasswordNull(employee_id, DigestUtils.md5DigestAsHex(password.getBytes()));
            return getLastSelectedApp(employee);
        }
        return getLastSelectedApp(employeeDao.getEmployeeByEmployeeIdAndPassword(employee_id, DigestUtils.md5DigestAsHex(password.getBytes()), tenant_id));
    }

    public Employee getLastSelectedApp(Employee employee) {
        if(employee == null) {
            return null;
        }
        String nowUsed = employee.getLast_use_app_id();
        List<App> appList = new ArrayList<>();
        if(nowUsed != null && !nowUsed.equals("")) {
            String[] nowUsedList = nowUsed.split(",");
            for (String used : nowUsedList) {
                App temp = appDao.getAppByAppId(used.split(" & ")[0], employee.getTenant_id());
                temp.setUsed_time(new Date(Long.parseLong(used.split(" & ")[1])));
                appList.add(temp);
            }
        }
        employee.setLast_use_app(appList);
        String nowUsedS = employee.getSelected_app_id();
        List<App> apps = new ArrayList<>();
        if(nowUsedS != null && !nowUsedS.equals("")) {
            String[] nowUsedSList = nowUsedS.split(",");
            for (String used : nowUsedSList) {
                apps.add(appDao.getAppByAppId(used, employee.getTenant_id()));
            }
        }
        employee.setSelected_app(apps);
        return employee;
    }

}
